<template>
	<view>
		<!-- 已移除全屏loading组件 -->
		
		<!-- 当付费弹框显示时，隐藏页面内容 -->
		<!-- <view class="card-view" v-show="!showCateConfirm">
			<image :src="bannerImage" mode="aspectFill" style="width: 100%; height: 200rpx;"></image>
		</view> -->

		<!-- <view style="height: calc(99vh - 200px);" v-show="!showCateConfirm">
			<view class="card-view">
				<tui-cascade-selection 
					:height="'950rpx'" 
					:itemList="cateList" 
					@complete="complete" 
					text="请选择题库"
					:defaultItemList="defaultCateList">
				</tui-cascade-selection>
			</view>
			
			<view style="width:90%; margin: 10rpx auto;" class="padding-bottom-xl">
				<tui-button shape="circle" shadow bold preventClick :disabled="questionCount == 0"
					@click="checkPay">{{btnText}}</tui-button>
			</view>
		</view> -->

		<login ref="login" v-on:succ="getCate"></login>

		<!-- 题库支付、激活弹窗组件 -->
		<kz-cate-pay ref="cate_pay" :cateId="cateId" :catePrice="catePrice" :showCateConfirm="showCateConfirm"
			:confirmCateContent="confirmCateContent" v-on:paySuccess="goTrain()" v-on:codeSuccess="goTrain()"
			v-on:cancel="closeDialog">
		</kz-cate-pay>
	</view>
</template>

<script>
	import cateApi from "@/common/api/cate.js"
	export default {
		data() {
			return {
				page: '',
				cateList: [],
				cateId: 0,
				cateName: '',
				questionCount: 0,
				btnText: '开始练习',
				mode: 'memory', // 默认改为记忆模式
				defaultCateList: [],
				
				// 新增：训练类型
				trainType: 'normal', // sequence(顺序刷题) / recite(背题模式) / normal(普通训练)
				showModeSelection: false, // 是否显示模式选择 - 默认不显示，直接使用记忆模式

				// 题库支付弹窗相关
				catePrice: 0.00,
				showCateConfirm: false,
				confirmCateContent: '',
				
				subjectId: 0,
				
				bannerImage: '',
				
				// 标志：是否来自首页传递的参数
				isFromHomePage: false,
			}
		},
		onLoad(e) {
			this.page = e?.page
			
			// 处理训练类型
			if (e?.mode) {
				this.trainType = e.mode
			}
			
			// 始终使用记忆模式，不显示模式选择
			this.mode = 'memory'
			
			// 处理从首页传递的分类信息
			if (e?.subjectId) {
				this.isFromHomePage = true
				this.cateId = parseInt(e.subjectId)
				this.cateName = e.subjectName || '题库分类'
				console.log('从首页接收到分类信息:', this.cateId, this.cateName)
			}
			
			this.getPageCache()
			this.subjectId = this.utils.getSubjectId()
			this.getCate()
		},
		methods: {
			// 递归查找分类路径
			findCategoryPath(categories, targetId, currentPath = []) {
				for (let category of categories) {
					// 当前路径加上这个分类
					let newPath = [...currentPath, {
						text: category.text,
						value: category.value
					}]
					
					// 如果找到目标分类，返回路径
					if (category.value == targetId) {
						return newPath
					}
					
					// 如果有子分类，递归查找
					if (category.children && category.children.length > 0) {
						let result = this.findCategoryPath(category.children, targetId, newPath)
						if (result) {
							return result
						}
					}
				}
				return null
			},
			
			// 获取缓存
			getPageCache() {
				let cdn_url = this.utils.getData('cdn_url')
				cdn_url = cdn_url ? cdn_url : ''
				
				let pageCache = this.utils.getData('page')
				console.log('pageCache', pageCache)
				if (pageCache && pageCache.cate_banner_image) {
					this.bannerImage = cdn_url + pageCache.cate_banner_image
					console.log('this.bannerImage', this.bannerImage)
				}
			},
			// 获取题库
			getCate() {
				this.http('cate/getThree', {
					kind: 'QUESTION',
					page: this.page,
					cate_id: this.subjectId
				}, 'post', false).then(res => {
					this.cateList = res.data

					// 优先处理从首页传递的分类信息
					if (this.isFromHomePage && this.cateId && this.cateName) {
						console.log('处理传递的分类信息:', this.cateId, this.cateName)
						
						// 在分类列表中找到完整的分类路径
						let foundPath = this.findCategoryPath(this.cateList, this.cateId)
						console.log('找到的分类路径:', foundPath)
						
						if (foundPath && foundPath.length > 0) {
							// 设置默认选中的分类路径
							this.defaultCateList = foundPath.map(item => item.text)
							console.log('设置defaultCateList:', this.defaultCateList)
							
							// 调用complete方法
							this.complete({
								value: this.cateId,
								result: foundPath
							})
						} else {
							// 如果没找到路径，至少设置当前分类
							this.complete({
								value: this.cateId,
								result: [{
									text: this.cateName,
									value: this.cateId
								}]
							})
						}
						return
					}

					// 模拟题库点击事件
					if (this.cateId) {
						this.complete({
							value: this.cateId,
							result: [{
								text: this.cateName
							}]
						})
					} else {
						let defaultCate = this.utils.getData('default_cate-QUESTION')
						console.log('defaultCate', defaultCate)
						if (defaultCate) {
							let lastCate = [...defaultCate.result].pop()
							console.log('lastCate', lastCate)
							
							let hasCate = false
							for (let j = 0; j < this.cateList.length; j++) {
								let cate = this.cateList[j]
								if (hasCate || cate.value == lastCate.value) {
									hasCate = true
									break
								}
								
								if (cate.children && cate.children.length > 0) {
									for (let k = 0; k < cate.children.length; k++) {
										let child_cate = cate.children[k]
										if (child_cate.value == lastCate.value) {
											hasCate = true
											break
										}
									}
								}
							}

							if (hasCate) {
								let defaultCateList = []
								for (let i = 0; i < defaultCate.result.length; i++) {
									defaultCateList.push(defaultCate.result[i].text)
								}
								this.defaultCateList = defaultCateList
								
								this.cateId = lastCate.value
								this.cateName = lastCate.text
								
								this.complete({
									value: this.cateId,
									result: [{
										text: this.cateName
									}]
								})
							}
						}
					}

					// this.defaultCateList = ["消防","灭火救援常识",]
				})

				// 不再需要这个重复的模拟点击事件
				// 因为上面已经处理了传递的分类信息
			},
			// 选择题库
			complete(e) {
				console.log(e);
				console.log('您选择的数据为：', e);

				this.cateId = e.value
				this.cateName = e.result[e.result.length - 1].text

				let params = {
					cate_id: this.cateId,
					just_get_count: 1,
				}

				this.$refs.login.afterMethod = () => {
					this.complete(e)
				}
				console.log('afterMethod', this.$refs.login.afterMethod)
				this.http('question/train', params, 'post', false).then(res => {
					if (res.code == 1) {
						this.questionCount = res.data.total
						if (this.questionCount) {
							this.btnText = '开始练习（' + this.questionCount + '题）'
							
							// 如果是从首页传递参数进来的，且有题目，自动开始练习
							if (this.isFromHomePage && this.questionCount > 0) {
								console.log('从首页传递参数，自动开始练习')
								// 延迟一下，确保UI更新完成
								setTimeout(() => {
									this.checkPay()
								}, 500)
							}
						} else {
							this.btnText = '当前分类无试题'
						}
					} else {
						this.utils.toast(res.msg)
					}
				})

			},
			// 检测题库是否已开通
			checkPay() {
				// 重置标志，避免后续手动选择时也自动开始
				this.isFromHomePage = false
				
				if (!this.cateId) {
					this.utils.toast('请先选择练习的题库')
					return
				}

				// 检测题库是否已开通
				cateApi.checkPay(this, this.cateId).then(res => {
					console.log('checkPay res', res)

					if (res.code != 1) {
						uni.showModal({
							title: '提示',
							content: res.msg,
							confirmText: '前往开通',
							success: (res) => {
								if (res.confirm) {
									// 使用redirectTo跳转到会员中心，关闭当前页面
									uni.redirectTo({
										url: '/pages/user/member-center?from_train=1'
									})
								} else if (res.cancel) {
									this.utils.goback()
								}
							}
						});
						return
					}

					// 无须支付
					if (res.data.status == 1) {
						this.goTrain()
						return
					} else if (res.data.status == 2) {
						this.catePrice = parseFloat(res.data.price)
						this.confirmCateContent = res.data.msg
						this.showCateConfirm = true
					}
				})
			},
			// 开始练习
			goTrain() {
				this.showCateConfirm = false
				this.showResult = false
				this.confirmCateContent = ''
				this.payResultContent = ''

				let targetPage = ''
				let params = `cateId=${this.cateId}&cateName=${encodeURIComponent(this.cateName)}&mode=${this.mode}`
				
				// 根据训练类型决定跳转页面
				if (this.trainType === 'recite') {
					// 背题模式：跳转到look页面，直接显示答案
					targetPage = 'look'
					params += '&trainType=recite'
				} else if (this.trainType === 'sequence') {
					// 顺序刷题：跳转到train页面，需要点击才显示答案
					targetPage = 'train'
					params += '&trainType=sequence'
				} else {
					// 普通训练模式
					targetPage = this.page == 'train' ? 'train' : 'look'
				}
				
				console.log('跳转到:', targetPage, '参数:', params, '训练类型:', this.trainType);
				
				// 使用redirectTo方法跳转，会关闭当前页面
				uni.redirectTo({
					url: `${targetPage}?${params}`
				})
			},
			closeDialog() {
				console.log('get emit closeDialog')
				this.showCateConfirm = false
				
				// 用户点击取消时直接返回上一页
				this.utils.goback()
			}
		}
	}
</script>

<style>
	.tn-radio__label {
		color: #333 !important;
		font-size: 15px !important;
	}
	
	.special-mode-tip {
		padding: 20rpx;
		background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
		border-radius: 12rpx;
		border-left: 4rpx solid #0ea5e9;
		margin-bottom: 20rpx;
	}
	
	.tip-text {
		color: #0c4a6e;
		font-size: 28rpx;
		font-weight: 500;
		line-height: 1.5;
	}
</style>